package com.liuguang.testassert.security;

import com.liuguang.testassert.dao.UserMapper;
import com.liuguang.testassert.pojo.Role;
import com.liuguang.testassert.vo.UserData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UserDetailServiceImpl
 * @Description：
 * @Author: wanghr
 * Date: 11:11 AM 2020/6/17
 * Version: 1.0
 */
@Slf4j
@Component
public class UserDetailServiceImpl {
    @Autowired
    private UserMapper userMapper;

    public Authentication loadUser(String username)  {

        UserData userData = userMapper.selectUserByUserName(username);
        List<Role> roleList = userData.getRole();
        int size = roleList.size();
        log.info("用户具有角色个数：{}",size);

        ArrayList<GrantedAuthority> authories = new ArrayList<>();
        if (size < 0) {
            throw  new RuntimeException("该用户没有角色");
        }
        for (Role role : roleList) {
            authories.add(new SimpleGrantedAuthority(role.getRol()));
        }
        log.info("用户的 authories：{}",authories);

        return new UsernamePasswordAuthenticationToken(userData.getUsername(),userData.getPassword(),authories);
    }
}
